Skip to content

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

Go

MUL-7737: feat(views): address bar for HTML attachment previews (#8873)

Jiayuan Zhang344ffaf1becd
diff --git a/apps/desktop/src/renderer/src/pages/attachment-preview-page.tsx b/apps/desktop/src/renderer/src/pages/attachment-preview-page.tsx
index e22b8b5b73..42bf2a8ed2 100644
--- a/apps/desktop/src/renderer/src/pages/attachment-preview-page.tsx
+++ b/apps/desktop/src/renderer/src/pages/attachment-preview-page.tsx
@@ -6,11 +6,17 @@ export function AttachmentPreviewRoute() {
const { id } = useParams<{ id: string }>();
const [searchParams] = useSearchParams();
const filename = searchParams.get("name") ?? undefined;
+ // Query and fragment the document opens at (the viewer's address bar).
+ const initialAddress = searchParams.get("loc") ?? undefined;
if (!id) return null;
return (
<ErrorBoundary resetKeys={[id]}>
- <AttachmentPreviewPage attachmentId={id} filename={filename} />
+ <AttachmentPreviewPage
+ attachmentId={id}
+ filename={filename}
+ initialAddress={initialAddress}
+ />
</ErrorBoundary>
);
}
diff --git a/apps/web/app/[workspaceSlug]/attachments/[id]/preview/page.tsx b/apps/web/app/[workspaceSlug]/attachments/[id]/preview/page.tsx
index ac57617f16..60569dceee 100644
--- a/apps/web/app/[workspaceSlug]/attachments/[id]/preview/page.tsx
+++ b/apps/web/app/[workspaceSlug]/attachments/[id]/preview/page.tsx
@@ -17,10 +17,16 @@ export default function AttachmentPreviewWebPage({
const { id } = use(params);
const search = useSearchParams();
const filename = search.get("name") ?? undefined;
+ // Query and fragment the document opens at (the viewer's address bar).
+ const initialAddress = search.get("loc") ?? undefined;
return (
<ErrorBoundary resetKeys={[id]}>
- <AttachmentPreviewPage attachmentId={id} filename={filename} />
+ <AttachmentPreviewPage
+ attachmentId={id}
+ filename={filename}
+ initialAddress={initialAddress}
+ />
</ErrorBoundary>
);
}
diff --git a/packages/views/attachments/attachment-preview-page.test.tsx b/packages/views/attachments/attachment-preview-page.test.tsx
index d875efcd22..5f666c9e69 100644
--- a/packages/views/attachments/attachment-preview-page.test.tsx
+++ b/packages/views/attachments/attachment-preview-page.test.tsx
@@ -1,14 +1,16 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { screen, waitFor } from "@testing-library/react";
+import { fireEvent, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactElement } from "react";
import type { Attachment } from "@multica/core/types";
import type { ScrollRestorationAdapter } from "../platform";
import { ScrollRestorationProvider } from "../platform";
import { renderWithI18n } from "../test/i18n";
-import { AttachmentPreviewPage } from "./attachment-preview-page";
+import { AttachmentPreviewPage, HTML_PREVIEW_ADDRESS_KEY } from "./attachment-preview-page";
import { hashString } from "../editor/utils/hash-string";
import { buildScrollBridge } from "../editor/utils/iframe-scroll-bridge";
+import { withFragmentNavShim } from "../editor/utils/iframe-fragment-nav";
+import { withLocationBridge } from "../editor/utils/iframe-location-bridge";
const htmlText = "<html><body><h1>Report</h1></body></html>";
@@ -88,6 +90,7 @@ describe("AttachmentPreviewPage", () => {
expect(await screen.findByTitle("report.html")).toBeTruthy();
expect(screen.getByText("report.html")).toBeTruthy();
+ expect(screen.getByRole("textbox", { name: "Address" })).toHaveValue("");
expect(screen.getByRole("button", { name: "Download" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Fit" })).toHaveAttribute("aria-pressed", "true");
expect(screen.queryByRole("button", { name: "Close" })).toBeNull();
@@ -123,10 +126,42 @@ describe("AttachmentPreviewPage", () => {
</ScrollRestorationProvider>,
);
const iframe = await screen.findByTitle("report.html");
- expect(iframe.getAttribute("srcdoc")).not.toContain("__multica");
- expect(iframe.getAttribute("srcdoc")).not.toContain(buildScrollBridge("x"));
- // Still applies the fragment-nav shim on both surfaces.
- expect(iframe.getAttribute("srcdoc")).toContain("scrollIntoView");
+ // The address bridge and the fragment-nav shim, but no scroll bridge.
+ expect(iframe.getAttribute("srcdoc")).toBe(
+ withLocationBridge(withFragmentNavShim(htmlText), ""),
+ );
+ });
+
+ it("opens an HTML file at the route's address", async () => {
+ renderPage(<AttachmentPreviewPage attachmentId="att-1" initialAddress="?s=ia" />);
+ const iframe = await screen.findByTitle("report.html");
+ expect(iframe.getAttribute("srcdoc")).toBe(
+ withLocationBridge(withFragmentNavShim(htmlText), "?s=ia"),
+ );
+ expect(screen.getByRole("textbox", { name: "Address" })).toHaveValue("?s=ia");
+ });
+
+ it("comes back to the address kept in the tab's view state, and keeps it there", async () => {
+ const views = new Map<string, string | undefined>([[HTML_PREVIEW_ADDRESS_KEY, "?s=kept"]]);
+ const adapter: ScrollRestorationAdapter = {
+ get: () => undefined,
+ getViewState: (key) => views.get(key),
+ setViewState: (key, value) => views.set(key, value),
+ };
+ renderPage(
+ <ScrollRestorationProvider adapter={adapter}>
+ <AttachmentPreviewPage attachmentId="att-1" initialAddress="?s=route" />
+ </ScrollRestorationProvider>,
+ );
+ const iframe = await screen.findByTitle("report.html");
+ expect(iframe.getAttribute("srcdoc")).toBe(
+ withLocationBridge(withFragmentNavShim(htmlText), "?s=kept"),
+ );
+
+ const input = screen.getByRole("textbox", { name: "Address" });
+ fireEvent.change(input, { target: { value: "?s=next" } });
+ fireEvent.submit(input.closest("form")!);
+ expect(views.get(HTML_PREVIEW_ADDRESS_KEY)).toBe("?s=next");
});
it("shows an image", async () => {
diff --git a/packages/views/attachments/attachment-preview-page.tsx b/packages/views/attachments/attachment-preview-page.tsx
index 9ba1948e0a..923845283d 100644
--- a/packages/views/attachments/attachment-preview-page.tsx
+++ b/packages/views/attachments/attachment-preview-page.tsx
@@ -21,28 +21,41 @@
* The route is workspace-scoped (`/{slug}/attachments/{id}/preview`) for
* tenancy isolation; the attachment endpoints themselves are auth-checked, so
* the slug is purely a URL contract.
+ *
+ * An HTML file opens at the `loc` the viewer handed over (its address bar,
+ * MUL-7737). On desktop the address the reader left is kept in the tab's
+ * view state, so a tab switch comes back to the same screen.
*/
-import { useEffect } from "react";
+import { useCallback, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { api } from "@multica/core/api";
import { useT } from "../i18n";
+import { useRestoredViewState, useViewStateWriter } from "../platform";
import {
AttachmentPreviewStandalone,
type HtmlFrameRenderer,
} from "../editor/attachment-preview-modal";
+import type { HtmlPreviewLocation } from "../editor/hooks/use-html-preview-location";
+import { normalizeHtmlPreviewAddress } from "../editor/utils/iframe-location-bridge";
import { useHtmlPreviewScrollRestore } from "./use-html-preview-scroll-restore";
+/** View-state key the page keeps an HTML file's address under. */
+export const HTML_PREVIEW_ADDRESS_KEY = "html-preview-address";
+
interface AttachmentPreviewPageProps {
attachmentId: string;
/** Optional display name. Titles the tab until the record has loaded. */
filename?: string;
+ /** Query and fragment an HTML file opens at (the route's `loc`). */
+ initialAddress?: string;
}
export function AttachmentPreviewPage({
attachmentId,
filename,
+ initialAddress,
}: AttachmentPreviewPageProps) {
const { t } = useT("editor");
const query = useQuery({
@@ -64,11 +77,22 @@ export function AttachmentPreviewPage({
if (title) document.title = title;
}, [title]);
+ const restoredAddress = useRestoredViewState(HTML_PREVIEW_ADDRESS_KEY);
+ const writeViewState = useViewStateWriter();
+ const keepAddress = useCallback(
+ (address: string) => writeViewState(HTML_PREVIEW_ADDRESS_KEY, address),
+ [writeViewState],
+ );
+
if (attachment) {
return (
<AttachmentPreviewStandalone
attachment={attachment}
renderHtmlFrame={renderPageHtmlFrame}
+ initialHtmlAddress={normalizeHtmlPreviewAddress(
+ restoredAddress ?? initialAddress ?? "",
+ )}
+ onHtmlAddressChange={keepAddress}
/>
);
}
@@ -94,15 +118,31 @@ export function AttachmentPreviewPage({
// content change (re-upload) structurally remounts a fresh document; the
// hook reports y=0 with the new key until that document scrolls, and
// messages from the previous document are dropped by token.
-function PageHtmlFrame({ html, title }: { html: string; title: string }) {
+function PageHtmlFrame({
+ html,
+ title,
+ location,
+}: {
+ html: string;
+ title: string;
+ location: HtmlPreviewLocation;
+}) {
const { contentKey, buildSrcDoc, iframeRef, onLoad } =
useHtmlPreviewScrollRestore(html);
+ const { frameRef } = location;
+ const setFrame = useCallback(
+ (el: HTMLIFrameElement | null) => {
+ iframeRef(el);
+ frameRef(el);
+ },
+ [iframeRef, frameRef],
+ );
return (
<iframe
- key={contentKey}
- ref={iframeRef}
+ key={`${contentKey}:${location.frameKey}`}
+ ref={setFrame}
onLoad={onLoad}
- srcDoc={buildSrcDoc(html)}
+ srcDoc={location.withAddress(buildSrcDoc(html))}
sandbox="allow-scripts"
title={title}
className="h-full w-full border-0 bg-background"
diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsx
index 0f2e3f3a16..c828856d0e 100644
--- a/packages/views/editor/attachment-preview-modal.test.tsx
+++ b/packages/views/editor/attachment-preview-modal.test.tsx
@@ -143,6 +143,9 @@ vi.mock("../i18n", () => ({
table_empty: "No rows",
table_rows: "rows",
table_columns: "columns",
+ address: "Address",
+ address_hint: "?query",
+ reload: "Reload",
},
}),
}),
@@ -152,6 +155,8 @@ import {
AttachmentPreviewModal,
useAttachmentPreview,
} from "./attachment-preview-modal";
+import { withFragmentNavShim } from "./utils/iframe-fragment-nav";
+import { withLocationBridge } from "./utils/iframe-location-bridge";
import { renderHook, act as hookAct } from "@testing-library/react";
// Fresh QueryClient per render — no retries (preview errors are typed,
@@ -308,12 +313,75 @@ describe("AttachmentPreviewModal — dispatch", () => {
// (MUL-2330). The combination with `allow-same-origin` would defeat
// the sandbox, so this assertion must stay exact.
expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
- // srcdoc carries the original HTML plus the fragment-nav shim
- // appended at the end (see utils/iframe-fragment-nav.ts).
- const srcdoc = frame?.getAttribute("srcdoc") ?? "";
- expect(srcdoc.startsWith("<p>hi</p>")).toBe(true);
- expect(srcdoc).toContain("scrollIntoView");
+ // srcdoc carries the original HTML between the address bridge in
+ // front (utils/iframe-location-bridge.ts) and the fragment-nav shim
+ // appended at the end (utils/iframe-fragment-nav.ts).
+ expect(frame?.getAttribute("srcdoc")).toBe(
+ withLocationBridge(withFragmentNavShim("<p>hi</p>"), ""),
+ );
+ });
+ });
+
+ it("loads the HTML at the address typed into its address bar", async () => {
+ getAttachmentTextContentMock.mockResolvedValueOnce({
+ text: "<p>hi</p>",
+ originalContentType: "text/html",
+ });
+ const att = makeAttachment({ filename: "mock.html", content_type: "text/html" });
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);
+
+ const input = await screen.findByLabelText("Address");
+ fireEvent.change(input, { target: { value: "mock.html?s=overview" } });
+ fireEvent.submit(input.closest("form")!);
+
+ const frame = document.querySelector("iframe[sandbox]") as HTMLIFrameElement;
+ expect(frame.getAttribute("srcdoc")).toBe(
+ withLocationBridge(withFragmentNavShim("<p>hi</p>"), "?s=overview"),
+ );
+ expect((input as HTMLInputElement).value).toBe("?s=overview");
+ });
+
+ it("keeps the HTML's address across the source view", async () => {
+ getAttachmentTextContentMock.mockResolvedValueOnce({
+ text: "<p>hi</p>",
+ originalContentType: "text/html",
});
+ const att = makeAttachment({ filename: "mock.html", content_type: "text/html" });
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);
+
+ const input = await screen.findByLabelText("Address");
+ fireEvent.change(input, { target: { value: "?s=ia" } });
+ fireEvent.submit(input.closest("form")!);
+ fireEvent.click(screen.getByRole("button", { name: "View source" }));
+ // The source is the file, not a page: no address, nothing to reload.
+ expect(screen.queryByLabelText("Address")).toBeNull();
+ expect(screen.getByText("mock.html", { selector: "p" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Reload" })).toBeDisabled();
+ fireEvent.click(screen.getByRole("button", { name: "View source" }));
+
+ expect(screen.getByLabelText("Address")).toHaveValue("?s=ia");
+ expect(document.querySelector("iframe[sandbox]")?.getAttribute("srcdoc")).toBe(
+ withLocationBridge(withFragmentNavShim("<p>hi</p>"), "?s=ia"),
+ );
+ });
+
+ it("drops an unsubmitted address on Escape without closing the viewer", async () => {
+ getAttachmentTextContentMock.mockResolvedValueOnce({
+ text: "<p>hi</p>",
+ originalContentType: "text/html",
+ });
+ const att = makeAttachment({ filename: "mock.html", content_type: "text/html" });
+ render(<ClosablePreview attachment={att} />);
+
+ const input = (await screen.findByLabelText("Address")) as HTMLInputElement;
+ fireEvent.change(input, { target: { value: "?s=draft" } });
+ fireEvent.keyDown(input, { key: "Escape" });
+ expect(input.value).toBe("");
+ expect(screen.getByRole("dialog")).toBeTruthy();
+
+ // With nothing left to drop, Escape closes the viewer as usual.
+ fireEvent.keyDown(input, { key: "Escape" });
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
});
it("renders a code block with lowlight for source files", async () => {
@@ -712,6 +780,33 @@ describe("AttachmentPreviewModal — open-in-new-tab", () => {
expect(onClose).toHaveBeenCalledTimes(1);
});
+ it("opens the new tab at the address the HTML is at", async () => {
+ getAttachmentTextContentMock.mockResolvedValueOnce({
+ text: "<p>hi</p>",
+ originalContentType: "text/html",
+ });
+ const att = makeAttachment({
+ filename: "report.html",
+ content_type: "text/html",
+ });
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "full", attachment: att }}
+ open
+ onClose={() => {}}
+ />,
+ );
+ const input = await screen.findByLabelText("Address");
+ fireEvent.change(input, { target: { value: "?s=ia#top" } });
+ fireEvent.submit(input.closest("form")!);
+ fireEvent.click(screen.getByTitle("Open in new tab"));
+ expect(openInNewTabMock).toHaveBeenCalledWith(
+ "/acme/attachments/att-1/preview?name=report.html&loc=%3Fs%3Dia%23top",
+ "report.html",
+ { activate: true },
+ );
+ });
+
it("falls back to window.open against the shareable URL and closes the modal (web)", async () => {
navState.hasOpenInNewTab = false;
getAttachmentTextContentMock.mockResolvedValueOnce({
diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsx
index b5f545f436..cfb0359302 100644
--- a/packages/views/editor/attachment-preview-modal.tsx
+++ b/packages/views/editor/attachment-preview-modal.tsx
@@ -82,6 +82,7 @@ import {
MessageSquareText,
Monitor,
PanelRight,
+ RotateCw,
Smartphone,
Tablet,
WrapText,
@@ -120,6 +121,11 @@ import { useZoomCanvas, type ZoomCanvasApi } from "./hooks/use-zoom-canvas";
import { ZoomCanvas, ZoomControls } from "./zoom-canvas";
import type { Size } from "./utils/zoom-transform";
import { HtmlPreviewBody } from "./html-preview-body";
+import { HtmlPreviewAddress } from "./html-preview-address";
+import {
+ useHtmlPreviewLocation,
+ type HtmlPreviewLocation,
+} from "./hooks/use-html-preview-location";
import { CodeBlockStatic } from "./code-block-static";
import { TablePreview } from "./table-preview";
import { StructuredTree } from "./structured-tree";
@@ -456,6 +462,17 @@ export function AttachmentPreviewModal({
// workspace route instead of throwing, so the new-tab button just hides.
const slug = useWorkspaceSlug();
const navigation = useNavigation();
+ // The html kind's current address, for "Open in new tab". Tagged with its
+ // file so one document's address never follows the reader to the next.
+ const htmlAddressRef = useRef<{ attachmentId: string; address: string } | null>(
+ null,
+ );
+ const handleHtmlAddressChange = useCallback(
+ (attachmentId: string, address: string) => {
+ htmlAddressRef.current = { attachmentId, address };
+ },
+ [],
+ );
const onPrev = sequence?.onPrev;
const onNext = sequence?.onNext;
@@ -528,10 +545,16 @@ export function AttachmentPreviewModal({
const canOpenInNewTab = kind !== null && !!slug && !!state.attachmentId;
const handleOpenInNewTab = () => {
if (!slug || !state.attachmentId) return;
- const nameQuery = state.filename
- ? `?name=${encodeURIComponent(state.filename)}`
- : "";
- const path = `${paths.workspace(slug).attachmentPreview(state.attachmentId)}${nameQuery}`;
+ const address =
+ htmlAddressRef.current?.attachmentId === state.attachmentId
+ ? htmlAddressRef.current.address
+ : "";
+ const params = [
+ state.filename ? `name=${encodeURIComponent(state.filename)}` : "",
+ address ? `loc=${encodeURIComponent(address)}` : "",
+ ].filter(Boolean);
+ const query = params.length > 0 ? `?${params.join("&")}` : "";
+ const path = `${paths.workspace(slug).attachmentPreview(state.attachmentId)}${query}`;
if (navigation.openInNewTab) {
navigation.openInNewTab(path, state.filename, { activate: true });
} else {
@@ -603,6 +626,7 @@ export function AttachmentPreviewModal({
info={info}
locate={locate}
onOpenOverview={onOpenOverview}
+ onHtmlAddressChange={handleHtmlAddressChange}
/>
</motion.div>
)}
@@ -637,15 +661,22 @@ const VIEWPORT_ICONS: Record<HtmlViewport, LucideIcon> = {
};
/**
- * Renders an HTML attachment's iframe. The viewer's is plain; the full-page
- * preview's also reports its scroll position to the desktop tab restorer.
+ * Renders an HTML attachment's iframe, loaded at the address bar's address
+ * (`location`, see useHtmlPreviewLocation). The viewer's is plain; the
+ * full-page preview's also reports its scroll position to the desktop tab
+ * restorer.
*/
-export type HtmlFrameRenderer = (props: { html: string; title: string }) => ReactNode;
+export type HtmlFrameRenderer = (props: {
+ html: string;
+ title: string;
+ location: HtmlPreviewLocation;
+}) => ReactNode;
-const renderViewerHtmlFrame: HtmlFrameRenderer = ({ html, title }) => (
+const renderViewerHtmlFrame: HtmlFrameRenderer = ({ html, title, location }) => (
<HtmlPreviewBody
html={html}
title={title}
+ location={location}
className="h-full w-full"
iframeClassName="rounded-none border-0"
/>
@@ -687,6 +718,8 @@ function PreviewPanel({
locate,
onOpenOverview,
renderHtmlFrame = renderViewerHtmlFrame,
+ initialHtmlAddress = "",
+ onHtmlAddressChange,
}: {
surface: "viewer" | "page";
kind: PreviewKind | null;
@@ -703,6 +736,10 @@ function PreviewPanel({
locate?: PreviewLocateAction;
onOpenOverview?: () => void;
renderHtmlFrame?: HtmlFrameRenderer;
+ /** Query and fragment an HTML file opens at. */
+ initialHtmlAddress?: string;
+ /** Reports an HTML file's address as the reader or the document moves it. */
+ onHtmlAddressChange?: (attachmentId: string, address: string) => void;
}) {
const { t } = useT("editor");
@@ -715,6 +752,18 @@ function PreviewPanel({
const toggleWrap = () => setWrapChoice(!wrap);
const [htmlViewport, setHtmlViewport] = useState<HtmlViewport>("fill");
const [htmlSource, setHtmlSource] = useState(false);
+ // An HTML file's address: shown in the top bar, loaded by the stage. Held
+ // here, per file, so it survives the source view, which unmounts the frame.
+ const htmlLocation = useHtmlPreviewLocation(
+ initialHtmlAddress,
+ state.attachmentId ?? "",
+ );
+ const htmlAddress = htmlLocation.address;
+ useEffect(() => {
+ if (kind === "html" && state.attachmentId) {
+ onHtmlAddressChange?.(state.attachmentId, htmlAddress);
+ }
+ }, [kind, state.attachmentId, htmlAddress, onHtmlAddressChange]);
const [structuredChoice, setStructuredChoice] = useState<StructuredView>("tree");
const structuredParse = useStructuredParse(state, kind === "structured");
const treeAvailable = structuredParse?.ok !== false;
@@ -726,6 +775,7 @@ function PreviewPanel({
structuredView,
structuredParse,
renderHtmlFrame,
+ htmlLocation,
};
// Gallery navigation hands this panel an attachment the reader never
@@ -827,7 +877,16 @@ function PreviewPanel({
</span>
<div className="min-w-0">
<div className="flex min-w-0 items-center gap-2" style={titleAccessory ? NO_DRAG : undefined}>
- <p className="truncate text-body font-medium">{state.filename}</p>
+ {kind === "html" && !htmlSource ? (
+ <HtmlPreviewAddress
+ filename={state.filename}
+ address={htmlLocation.address}
+ onNavigate={htmlLocation.navigate}
+ style={NO_DRAG}
+ />
+ ) : (
+ <p className="truncate text-body font-medium">{state.filename}</p>
+ )}
{titleAccessory}
</div>
{meta.length > 0 && (
@@ -868,6 +927,13 @@ function PreviewPanel({
toggling the source view must not shift the button just pressed. */}
{kind === "html" && (
<>
+ <ChromeButton
+ label={t(($) => $.attachment.reload)}
+ disabled={htmlSource}
+ onClick={htmlLocation.reload}
+ >
+ <RotateCw className="size-4" />
+ </ChromeButton>
<ChromeSegmented
label={t(($) => $.attachment.viewport)}
value={htmlViewport}
@@ -1251,6 +1317,7 @@ interface StageView {
/** The `structured` kind's parse, once its body has loaded. */
structuredParse: ReturnType<typeof parseStructured> | null;
renderHtmlFrame: HtmlFrameRenderer;
+ htmlLocation: HtmlPreviewLocation;
}
const TEXT_BACKED_KINDS: ReadonlySet<PreviewKind> = new Set<PreviewKind>([
@@ -1374,7 +1441,11 @@ function PreviewContent({
code(text, "xml")
) : (
<HtmlViewportFrame viewport={view.htmlViewport}>
- {view.renderHtmlFrame({ html: text, title: state.filename })}
+ {view.renderHtmlFrame({
+ html: text,
+ title: state.filename,
+ location: view.htmlLocation,
+ })}
</HtmlViewportFrame>
)
}
@@ -1564,9 +1635,14 @@ function UnsupportedFallback({
export function AttachmentPreviewStandalone({
attachment,
renderHtmlFrame,
+ initialHtmlAddress,
+ onHtmlAddressChange,
}: {
attachment: Attachment;
renderHtmlFrame?: HtmlFrameRenderer;
+ /** Query and fragment an HTML file opens at. */
+ initialHtmlAddress?: string;
+ onHtmlAddressChange?: (address: string) => void;
}) {
const download = useDownloadAttachment();
const source = useMemo<PreviewSource>(
@@ -1574,6 +1650,10 @@ export function AttachmentPreviewStandalone({
[attachment],
);
const state = normalize(source);
+ const handleHtmlAddressChange = useCallback(
+ (_attachmentId: string, address: string) => onHtmlAddressChange?.(address),
+ [onHtmlAddressChange],
+ );
return (
<div className="flex h-full w-full flex-col bg-black/95">
@@ -1585,6 +1665,8 @@ export function AttachmentPreviewStandalone({
onDownload={() => download(attachment.id)}
reduceMotion
renderHtmlFrame={renderHtmlFrame}
+ initialHtmlAddress={initialHtmlAddress}
+ onHtmlAddressChange={handleHtmlAddressChange}
/>
</div>
);
diff --git a/packages/views/editor/hooks/use-html-preview-location.test.tsx b/packages/views/editor/hooks/use-html-preview-location.test.tsx
new file mode 100644
index 0000000000..d9273f6950
--- /dev/null
+++ b/packages/views/editor/hooks/use-html-preview-location.test.tsx
@@ -0,0 +1,119 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import { useHtmlPreviewLocation } from "./use-html-preview-location";
+import {
+ HTML_PREVIEW_LOCATION_KEY as K,
+ withLocationBridge,
+} from "../utils/iframe-location-bridge";
+
+function mountFrame() {
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ const postMessage = vi.spyOn(iframe.contentWindow!, "postMessage");
+ return { iframe, postMessage };
+}
+
+function post(source: Window | null, data: unknown) {
+ act(() => {
+ window.dispatchEvent(new MessageEvent("message", { data, source }));
+ });
+}
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+});
+
+describe("useHtmlPreviewLocation", () => {
+ it("loads the document at the initial address", () => {
+ const { result } = renderHook(() => useHtmlPreviewLocation("?s=ia"));
+ expect(result.current.address).toBe("?s=ia");
+ expect(result.current.withAddress("<p>x</p>")).toBe(withLocationBridge("<p>x</p>", "?s=ia"));
+ });
+
+ it("follows the address its own frame reports, and no other window's", () => {
+ const { iframe } = mountFrame();
+ const other = mountFrame().iframe;
+ const { result } = renderHook(() => useHtmlPreviewLocation());
+ act(() => result.current.frameRef(iframe));
+
+ post(other.contentWindow, { [K]: 1, type: "location", value: "?s=spoof" });
+ expect(result.current.address).toBe("");
+
+ post(iframe.contentWindow, { [K]: 1, type: "location", value: "?s=b#top" });
+ expect(result.current.address).toBe("?s=b#top");
+ // In-document navigation does not reload the frame.
+ expect(result.current.frameKey).toBe(0);
+ });
+
+ it("reloads the frame for a new query", () => {
+ const { iframe, postMessage } = mountFrame();
+ const { result } = renderHook(() => useHtmlPreviewLocation("?s=a"));
+ act(() => result.current.frameRef(iframe));
+
+ act(() => result.current.navigate("?s=b#top"));
+ expect(result.current.frameKey).toBe(1);
+ expect(result.current.address).toBe("?s=b#top");
+ expect(result.current.withAddress("")).toBe(withLocationBridge("", "?s=b#top"));
+ expect(postMessage).not.toHaveBeenCalled();
+ });
+
+ it("sends a fragment-only change to the running document instead of reloading", () => {
+ const { iframe, postMessage } = mountFrame();
+ const { result } = renderHook(() => useHtmlPreviewLocation("?s=a"));
+ act(() => result.current.frameRef(iframe));
+
+ act(() => result.current.navigate("?s=a#anatomy"));
+ expect(result.current.frameKey).toBe(0);
+ expect(postMessage).toHaveBeenCalledWith({ [K]: 1, type: "hash", value: "#anatomy" }, "*");
+ });
+
+ it("reloads at the address the document navigated to", () => {
+ const { iframe } = mountFrame();
+ const { result } = renderHook(() => useHtmlPreviewLocation("?s=a"));
+ act(() => result.current.frameRef(iframe));
+ post(iframe.contentWindow, { [K]: 1, type: "location", value: "?s=c" });
+
+ act(() => result.current.reload());
+ expect(result.current.frameKey).toBe(1);
+ expect(result.current.withAddress("")).toBe(withLocationBridge("", "?s=c"));
+ });
+
+ it("starts another document over at the initial address, in a fresh frame", () => {
+ const { result, rerender } = renderHook(
+ ({ scope }) => useHtmlPreviewLocation("?s=start", scope),
+ { initialProps: { scope: "file-a" } },
+ );
+ act(() => result.current.navigate("?s=elsewhere"));
+ expect(result.current.address).toBe("?s=elsewhere");
+
+ rerender({ scope: "file-b" });
+ expect(result.current.address).toBe("?s=start");
+ expect(result.current.withAddress("")).toBe(withLocationBridge("", "?s=start"));
+ expect(result.current.frameKey).toBe(2);
+ });
+
+ it("follows a link's navigate request only right after a click", () => {
+ const { iframe } = mountFrame();
+ // jsdom has no user activation; model the browser's.
+ const activation = { isActive: false };
+ Object.defineProperty(navigator, "userActivation", {
+ configurable: true,
+ value: activation,
+ });
+ try {
+ const { result } = renderHook(() => useHtmlPreviewLocation());
+ act(() => result.current.frameRef(iframe));
+
+ post(iframe.contentWindow, { [K]: 1, type: "navigate", value: "?s=loop" });
+ expect(result.current.frameKey).toBe(0);
+
+ activation.isActive = true;
+ post(iframe.contentWindow, { [K]: 1, type: "navigate", value: "?s=next" });
+ expect(result.current.frameKey).toBe(1);
+ expect(result.current.address).toBe("?s=next");
+ } finally {
+ delete (navigator as { userActivation?: unknown }).userActivation;
+ }
+ });
+});
diff --git a/packages/views/editor/hooks/use-html-preview-location.ts b/packages/views/editor/hooks/use-html-preview-location.ts
new file mode 100644
index 0000000000..8d4698ff20
--- /dev/null
+++ b/packages/views/editor/hooks/use-html-preview-location.ts
@@ -0,0 +1,123 @@
+"use client";
+
+/**
+ * useHtmlPreviewLocation — the parent side of the preview's address bar
+ * (MUL-7737; the in-iframe half is utils/iframe-location-bridge.ts).
+ *
+ * Owns two things: the address the document was loaded at, which is baked
+ * into its srcdoc, and the address it is at now, which the bridge reports as
+ * the document navigates itself. A new query means a new document, so
+ * navigating to one reloads the frame through `frameKey`; a fragment-only
+ * change is sent to the running document instead, the way a browser keeps
+ * the page for `#section`.
+ */
+
+import { useCallback, useLayoutEffect, useRef, useState } from "react";
+import {
+ HTML_PREVIEW_LOCATION_KEY,
+ readHtmlPreviewLocationMessage,
+ splitHtmlPreviewAddress,
+ withLocationBridge,
+} from "../utils/iframe-location-bridge";
+
+export interface HtmlPreviewLocation {
+ /** Where the document is now: `"?s=overview#top"`, or `""`. */
+ address: string;
+ /** Bumped on every fresh load; part of the iframe's React key. */
+ frameKey: number;
+ /** The srcdoc for the current load: the bridge, then `html`. */
+ withAddress: (html: string) => string;
+ /** iframe ref — identifies which window's messages to trust. */
+ frameRef: (el: HTMLIFrameElement | null) => void;
+ navigate: (address: string) => void;
+ /** Loads the document afresh at its current address. */
+ reload: () => void;
+}
+
+export function useHtmlPreviewLocation(
+ initialAddress = "",
+ /** The document's identity; another one starts over at `initialAddress`. */
+ scope = "",
+): HtmlPreviewLocation {
+ const [state, setState] = useState({
+ scope,
+ /** The address baked into the current load's srcdoc. */
+ loaded: initialAddress,
+ /** Where the document is now. */
+ address: initialAddress,
+ key: 0,
+ });
+ // The viewer pages to another file without remounting: its document starts
+ // at the initial address, in a fresh frame, instead of the one left behind.
+ let current = state;
+ if (state.scope !== scope) {
+ current = { scope, loaded: initialAddress, address: initialAddress, key: state.key + 1 };
+ setState(current);
+ }
+ const { address, loaded, key } = current;
+ const frameElRef = useRef<HTMLIFrameElement | null>(null);
+ // Latest address for the stable callbacks below; updated during render,
+ // which is idempotent across re-renders.
+ const addressRef = useRef(address);
+ addressRef.current = address;
+
+ const loadAt = useCallback((next: string) => {
+ setState((previous) => ({
+ ...previous,
+ loaded: next,
+ address: next,
+ key: previous.key + 1,
+ }));
+ }, []);
+
+ const navigate = useCallback(
+ (next: string) => {
+ const from = splitHtmlPreviewAddress(addressRef.current);
+ const to = splitHtmlPreviewAddress(next);
+ const win = frameElRef.current?.contentWindow;
+ if (win && to.hash && to.search === from.search) {
+ win.postMessage({ [HTML_PREVIEW_LOCATION_KEY]: 1, type: "hash", value: to.hash }, "*");
+ return;
+ }
+ loadAt(next);
+ },
+ [loadAt],
+ );
+
+ const reload = useCallback(() => loadAt(addressRef.current), [loadAt]);
+
+ // Layout effect so the listener is in place before the document's first
+ // report, which it posts while it is still parsing.
+ useLayoutEffect(() => {
+ const onMessage = (event: MessageEvent) => {
+ const win = frameElRef.current?.contentWindow;
+ if (!win || event.source !== win) return;
+ const message = readHtmlPreviewLocationMessage(event.data);
+ if (!message) return;
+ if (message.type === "location") {
+ const value = message.value;
+ setState((previous) => ({ ...previous, address: value }));
+ return;
+ }
+ // A navigate request stands for a click on a `?…` link. Activation
+ // from a click inside the frame reaches this window too, so a document
+ // that posts the request on its own, e.g. on every load, cannot keep
+ // reloading itself.
+ if (navigator.userActivation && !navigator.userActivation.isActive) return;
+ loadAt(message.value);
+ };
+ window.addEventListener("message", onMessage);
+ return () => window.removeEventListener("message", onMessage);
+ }, [loadAt]);
+
+ const frameRef = useCallback((el: HTMLIFrameElement | null) => {
+ frameElRef.current = el;
+ }, []);
+
+ const withAddress = useCallback(
+ (html: string) => withLocationBridge(html, loaded),
+ [loaded],
+ );
+
+ return { address, frameKey: key, withAddress, frameRef, navigate, reload };
+}
diff --git a/packages/views/editor/html-preview-address.tsx b/packages/views/editor/html-preview-address.tsx
new file mode 100644
index 0000000000..3245c7c0ca
--- /dev/null
+++ b/packages/views/editor/html-preview-address.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+/**
+ * HtmlPreviewAddress — an HTML file's name in the viewer's top bar, as the
+ * address the document is at (MUL-7737), driven by useHtmlPreviewLocation.
+ *
+ * The file name is the fixed part; the query and fragment after it are the
+ * editable part. A document at its bare address reads as just the file name,
+ * so files that never use an address look as they always did; hovering or
+ * focusing shows the field. The field follows the document until the reader
+ * starts typing, and an edit that is not submitted is dropped on blur or
+ * Escape, as in a browser's address bar.
+ */
+
+import {
+ useRef,
+ useState,
+ type CSSProperties,
+ type KeyboardEvent,
+} from "react";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../i18n";
+import { normalizeHtmlPreviewAddress } from "./utils/iframe-location-bridge";
+
+interface HtmlPreviewAddressProps {
+ filename: string;
+ address: string;
+ onNavigate: (address: string) => void;
+ className?: string;
+ style?: CSSProperties;
+}
+
+export function HtmlPreviewAddress({
+ filename,
+ address,
+ onNavigate,
+ className,
+ style,
+}: HtmlPreviewAddressProps) {
+ const { t } = useT("editor");
+ const inputRef = useRef<HTMLInputElement>(null);
+ // null while the reader is not editing: the field follows the document.
+ const [draft, setDraft] = useState<string | null>(null);
+ const value = draft ?? address;
+ const hint = t(($) => $.attachment.address_hint);
+
+ const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key !== "Escape" || draft === null || draft === address) return;
+ // Revert the edit; the Escape does not reach the viewer, which would close.
+ e.stopPropagation();
+ setDraft(null);
+ };
+
+ return (
+ <form
+ className={cn(
+ "group/address -mx-1.5 flex h-6 min-w-0 cursor-text items-center rounded-md px-1.5 text-body transition-colors hover:bg-secondary focus-within:bg-secondary focus-within:ring-2 focus-within:ring-ring/50",
+ className,
+ )}
+ style={style}
+ // Anywhere on the field edits the address, the file name included.
+ onMouseDown={(e) => {
+ if (e.target === inputRef.current) return;
+ e.preventDefault();
+ inputRef.current?.focus();
+ }}
+ onSubmit={(e) => {
+ e.preventDefault();
+ onNavigate(normalizeHtmlPreviewAddress(value, filename));
+ setDraft(null);
+ }}
+ >
+ <span className="min-w-0 truncate font-medium">{filename}</span>
+ {/* Sized by an invisible copy of its text, so the address sits flush
+ against the file name. Empty, it takes no room until the field is
+ hovered or focused, when the hint shows where to type. */}
+ <span
+ data-empty={value === "" || undefined}
+ className="inline-grid min-w-0 max-w-[70%] shrink-0 overflow-hidden data-empty:w-0 group-hover/address:data-empty:w-auto group-focus-within/address:data-empty:w-auto"
+ >
+ <span
+ aria-hidden
+ className="invisible col-start-1 row-start-1 whitespace-pre"
+ >
+ {value || hint}
+ </span>
+ <input
+ ref={inputRef}
+ // No intrinsic width of its own: the copy above sizes the field.
+ size={1}
+ value={value}
+ placeholder={hint}
+ aria-label={t(($) => $.attachment.address)}
+ spellCheck={false}
+ autoComplete="off"
+ autoCapitalize="off"
+ autoCorrect="off"
+ enterKeyHint="go"
+ className="col-start-1 row-start-1 w-full min-w-0 bg-transparent text-foreground outline-none placeholder:text-muted-foreground"
+ onChange={(e) => setDraft(e.target.value)}
+ onFocus={(e) => e.currentTarget.select()}
+ onBlur={() => setDraft(null)}
+ onKeyDown={handleKeyDown}
+ />
+ </span>
+ </form>
+ );
+}
diff --git a/packages/views/editor/html-preview-body.tsx b/packages/views/editor/html-preview-body.tsx
index 8e4a99cd14..040236cf35 100644
--- a/packages/views/editor/html-preview-body.tsx
+++ b/packages/views/editor/html-preview-body.tsx
@@ -4,23 +4,27 @@
* HtmlPreviewBody — an HTML document in the sandboxed preview iframe, for the
* attachment viewer's html kind (the caller has already fetched the text).
*
- * Owns the two things every HTML preview needs:
+ * Owns the three things every HTML attachment preview needs:
*
* - srcDoc + sandbox="allow-scripts" via CodeBlockIframe
* - withFragmentNavShim() so anchor links inside the iframe scroll instead
* of silently failing in the sandbox's opaque origin
+ * - the address bridge, so the document loads at the address bar's
+ * address (`location`, owned by the stage — useHtmlPreviewLocation)
*
* A ```html block in a message body is a dynamic block instead
* (html-block-preview.tsx): it adds theme tokens and a size/error bridge.
*/
import { CodeBlockIframe } from "./code-block-iframe";
+import type { HtmlPreviewLocation } from "./hooks/use-html-preview-location";
import { withFragmentNavShim } from "./utils/iframe-fragment-nav";
interface HtmlPreviewBodyProps {
html: string;
/** iframe title attribute (a11y). */
title: string;
+ location: HtmlPreviewLocation;
/** Tailwind height/sizing classes for the iframe (e.g. "h-full"). */
className?: string;
/** Override iframe styling (border / radius). Tailwind-merge resolves
@@ -31,12 +35,16 @@ interface HtmlPreviewBodyProps {
export function HtmlPreviewBody({
html,
title,
+ location,
className,
iframeClassName,
}: HtmlPreviewBodyProps) {
return (
<CodeBlockIframe
- html={withFragmentNavShim(html)}
+ // A new frame for every fresh load at a new address.
+ key={location.frameKey}
+ ref={location.frameRef}
+ html={location.withAddress(withFragmentNavShim(html))}
title={title}
heightClassName={className}
className={iframeClassName}
diff --git a/packages/views/editor/utils/iframe-location-bridge.test.ts b/packages/views/editor/utils/iframe-location-bridge.test.ts
new file mode 100644
index 0000000000..1533980076
--- /dev/null
+++ b/packages/views/editor/utils/iframe-location-bridge.test.ts
@@ -0,0 +1,235 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ __locationBridgeScript__,
+ HTML_PREVIEW_LOCATION_KEY as K,
+ normalizeHtmlPreviewAddress,
+ readHtmlPreviewLocationMessage,
+ splitHtmlPreviewAddress,
+ withLocationBridge,
+} from "./iframe-location-bridge";
+
+const PREFIX_RE = /^<script>\(function\(\)\{[^\n]*\}\)\(\);<\/script>/;
+
+describe("withLocationBridge", () => {
+ it("puts the bridge after a leading doctype so the document stays in standards mode", () => {
+ const out = withLocationBridge("<!doctype html><p>hi</p>", "");
+ expect(out.startsWith("<!doctype html><script>")).toBe(true);
+ expect(out.endsWith("<p>hi</p>")).toBe(true);
+ });
+
+ it("keeps comments that precede the doctype in front of it", () => {
+ const out = withLocationBridge("<!-- mock -->\n<!DOCTYPE html><p>hi</p>", "");
+ expect(out.startsWith("<!-- mock -->\n<!DOCTYPE html><script>")).toBe(true);
+ });
+
+ it("prepends the bridge to a document without a doctype, on one line", () => {
+ const out = withLocationBridge("<p>hi</p>", "?s=1");
+ expect(out).toMatch(PREFIX_RE);
+ expect(out.endsWith("</script><p>hi</p>")).toBe(true);
+ });
+
+ it("cannot be closed early by the address it carries", () => {
+ const out = withLocationBridge("<p>hi</p>", "?x=</script><script>alert(1)</script>");
+ expect(out.match(/<\/script>/g)).toHaveLength(1);
+ });
+});
+
+describe("normalizeHtmlPreviewAddress", () => {
+ it.each([
+ ["", ""],
+ [" ", ""],
+ ["?s=overview", "?s=overview"],
+ [" ?s=overview#top ", "?s=overview#top"],
+ ["#anatomy", "#anatomy"],
+ ["mock.html?s=ia", "?s=ia"],
+ ["https://example.com/other.html#x", "#x"],
+ ["s=ia", "?s=ia"],
+ ["mock.html", ""],
+ ])("%j → %j", (input, expected) => {
+ expect(normalizeHtmlPreviewAddress(input, "mock.html")).toBe(expected);
+ });
+
+ it("caps the length", () => {
+ expect(normalizeHtmlPreviewAddress(`?${"a".repeat(5000)}`)).toHaveLength(2048);
+ });
+});
+
+describe("splitHtmlPreviewAddress", () => {
+ it.each([
+ ["", { search: "", hash: "" }],
+ ["?s=1", { search: "?s=1", hash: "" }],
+ ["#top", { search: "", hash: "#top" }],
+ ["?s=1#top", { search: "?s=1", hash: "#top" }],
+ ])("%j", (address, expected) => {
+ expect(splitHtmlPreviewAddress(address)).toEqual(expected);
+ });
+});
+
+describe("readHtmlPreviewLocationMessage", () => {
+ it("accepts a location report and a navigate request", () => {
+ expect(readHtmlPreviewLocationMessage({ [K]: 1, type: "location", value: "?s=1#a" })).toEqual({
+ type: "location",
+ value: "?s=1#a",
+ });
+ expect(readHtmlPreviewLocationMessage({ [K]: 1, type: "location", value: "" })).toEqual({
+ type: "location",
+ value: "",
+ });
+ expect(readHtmlPreviewLocationMessage({ [K]: 1, type: "navigate", value: "?s=2" })).toEqual({
+ type: "navigate",
+ value: "?s=2",
+ });
+ });
+
+ it.each([
+ ["no marker", { type: "location", value: "?s=1" }],
+ ["unknown type", { [K]: 1, type: "hash", value: "#a" }],
+ ["non-string value", { [K]: 1, type: "location", value: 1 }],
+ ["a path, not a query or fragment", { [K]: 1, type: "location", value: "/evil" }],
+ ["a full URL", { [K]: 1, type: "navigate", value: "https://evil.test/?x" }],
+ ["an empty navigate", { [K]: 1, type: "navigate", value: "" }],
+ ["an oversized value", { [K]: 1, type: "location", value: `?${"a".repeat(3000)}` }],
+ ["null", null],
+ ["a string", "?s=1"],
+ ])("rejects %s", (_label, data) => {
+ expect(readHtmlPreviewLocationMessage(data)).toBeNull();
+ });
+});
+
+// The bridge ships as a <script> string injected into a srcdoc iframe. Like
+// iframe-fragment-nav.test.ts, evaluate it against the current jsdom
+// document, whose `parent` is itself; its postMessage is stubbed to capture
+// what the bridge reports. Each load's listeners and History wrappers are
+// removed after the test so loads never stack. (The iframe's real
+// `about:srcdoc` URL is Chromium/WebKit behavior jsdom does not model; its
+// http URL exercises the same code paths.)
+let unload: (() => void) | null = null;
+
+function loadBridge(address = "") {
+ const postMessage = vi.spyOn(window, "postMessage").mockImplementation(() => {});
+ const listeners: Array<[string, EventListenerOrEventListenerObject]> = [];
+ const add = window.addEventListener.bind(window);
+ const spy = vi
+ .spyOn(window, "addEventListener")
+ .mockImplementation((type: string, listener: EventListenerOrEventListenerObject | null) => {
+ if (!listener) return;
+ listeners.push([type, listener]);
+ add(type, listener);
+ });
+ new Function(__locationBridgeScript__(address))();
+ spy.mockRestore();
+ unload = () => {
+ for (const [type, listener] of listeners) window.removeEventListener(type, listener);
+ delete (window.history as Partial<History>).pushState;
+ delete (window.history as Partial<History>).replaceState;
+ };
+ const messages = (type: string) =>
+ postMessage.mock.calls
+ .map(([m]) => m as { type: string; value: string })
+ .filter((m) => m.type === type)
+ .map((m) => m.value);
+ return {
+ reported: () => messages("location"),
+ navigations: () => messages("navigate"),
+ };
+}
+
+function hashChanged() {
+ return new Promise<void>((resolve) =>
+ window.addEventListener("hashchange", () => resolve(), { once: true }),
+ );
+}
+
+function addLink(href: string, attrs: Record<string, string> = {}) {
+ const link = document.createElement("a");
+ link.setAttribute("href", href);
+ for (const [name, value] of Object.entries(attrs)) link.setAttribute(name, value);
+ document.body.appendChild(link);
+ return link;
+}
+
+function click(el: Element, init: MouseEventInit = {}) {
+ const event = new MouseEvent("click", { bubbles: true, cancelable: true, ...init });
+ el.dispatchEvent(event);
+ return event;
+}
+
+describe("location bridge runtime", () => {
+ beforeEach(() => {
+ window.history.replaceState(null, "", "/doc");
+ });
+
+ afterEach(() => {
+ unload?.();
+ unload = null;
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+ });
+
+ it("opens the document at the initial address and reports it", () => {
+ const { reported } = loadBridge("?s=ia#anatomy");
+ expect(window.location.search).toBe("?s=ia");
+ expect(window.location.hash).toBe("#anatomy");
+ expect(new URLSearchParams(window.location.search).get("s")).toBe("ia");
+ expect(reported()).toEqual(["?s=ia#anatomy"]);
+ });
+
+ it("leaves the URL alone when opened at the bare address", () => {
+ const { reported } = loadBridge();
+ expect(window.location.pathname + window.location.search).toBe("/doc");
+ expect(reported()).toEqual([""]);
+ });
+
+ it("resolves relative pushState / replaceState URLs against the document and reports them", () => {
+ const { reported } = loadBridge("?s=a");
+ window.history.pushState({ n: 1 }, "", "?s=b");
+ expect(window.location.search).toBe("?s=b");
+ expect(window.history.state).toEqual({ n: 1 });
+ window.history.replaceState(null, "", "#top");
+ expect(window.location.pathname + window.location.search + window.location.hash).toBe(
+ "/doc?s=b#top",
+ );
+ expect(reported()).toEqual(["?s=a", "?s=b", "?s=b#top"]);
+ });
+
+ it("turns a click on a ?… link into a navigate request", () => {
+ const { navigations } = loadBridge();
+ const event = click(addLink("?s=next"));
+ expect(event.defaultPrevented).toBe(true);
+ expect(navigations()).toEqual(["?s=next"]);
+ expect(window.location.search).toBe("");
+ });
+
+ it("makes a #… link with no target a real hash change", async () => {
+ const { reported } = loadBridge();
+ const changed = hashChanged();
+ click(addLink("#/settings"));
+ await changed;
+ expect(window.location.hash).toBe("#/settings");
+ expect(reported()).toContain("#/settings");
+ });
+
+ it("leaves a click alone once something else claimed it, or when it opens elsewhere", () => {
+ const { navigations } = loadBridge();
+ const claimed = addLink("?s=1");
+ claimed.addEventListener("click", (e) => e.preventDefault());
+ click(claimed);
+ click(addLink("?s=2", { target: "_blank" }));
+ click(addLink("?s=3"), { metaKey: true });
+ expect(navigations()).toEqual([]);
+ });
+
+ it("applies a hash sent by the parent, and only by the parent", async () => {
+ loadBridge("?s=a");
+ window.dispatchEvent(
+ new MessageEvent("message", { data: { [K]: 1, type: "hash", value: "#ignored" }, source: null }),
+ );
+ expect(window.location.hash).toBe("");
+ const changed = hashChanged();
+ window.dispatchEvent(
+ new MessageEvent("message", { data: { [K]: 1, type: "hash", value: "#section" }, source: window }),
+ );
+ await changed;
+ expect(window.location.search + window.location.hash).toBe("?s=a#section");
+ });
+});
diff --git a/packages/views/editor/utils/iframe-location-bridge.ts b/packages/views/editor/utils/iframe-location-bridge.ts
new file mode 100644
index 0000000000..52b427cfe7
--- /dev/null
+++ b/packages/views/editor/utils/iframe-location-bridge.ts
@@ -0,0 +1,138 @@
+/**
+ * Address bridge for the HTML attachment preview's address bar (MUL-7737).
+ *
+ * The preview mounts the document as `<iframe sandbox="allow-scripts"
+ * srcdoc>`, so its URL is `about:srcdoc` and `location.search` is always
+ * empty. A self-contained mock that picks its screen with `?s=overview` —
+ * the convention agent-built mocks use — could only ever show its default
+ * screen. Relative URLs are no help either: a srcdoc document resolves them
+ * against the host page, so `?s=x` or `#x` in a link or a `pushState` call
+ * points at the app, not at the document.
+ *
+ * Chromium and WebKit let an opaque-origin document rewrite the query and
+ * fragment of its own URL through the History API, so a script placed in
+ * front of the author's markup can give the document a real address before
+ * any of the author's scripts read it. The same script:
+ *
+ * - resolves `?…` / `#…` arguments to pushState / replaceState against the
+ * document instead of the host page, so they stop throwing;
+ * - reports the address to the parent whenever it changes, so the bar
+ * follows in-document navigation;
+ * - turns a click on a `?…` link into a navigate request for the parent,
+ * which reloads the document at that address, and a click on a `#…` link
+ * the fragment-nav shim left alone (no element with that id — a hash
+ * router's link) into a real hash change;
+ * - applies a hash the parent sends, so a fragment-only address change
+ * navigates in place instead of reloading.
+ *
+ * It runs in the iframe's own opaque origin with the same capabilities the
+ * author's scripts already have; it cannot reach the parent. The parent
+ * treats every message as untrusted (see readHtmlPreviewLocationMessage).
+ * Where the History API refuses the rewrite, the address stays empty and the
+ * document renders exactly as before.
+ */
+
+/** Marker on every bridge message, in both directions. */
+export const HTML_PREVIEW_LOCATION_KEY = "__multicaHtmlLocation";
+
+/** Upper bound on an address; anything longer is not an address we keep. */
+export const HTML_PREVIEW_ADDRESS_MAX_LENGTH = 2048;
+
+// One line, so it sits on the author's first line and the line numbers in a
+// script error still point at the author's own source.
+function buildScript(initialAddress: string): string {
+ // `<` is escaped so an address can never close the script element.
+ const initial = JSON.stringify(initialAddress).replace(/</g, "\\u003c");
+ return [
+ "(function(){",
+ `var K=${JSON.stringify(HTML_PREVIEW_LOCATION_KEY)},H=window.history,L=window.location;`,
+ "var BASE=L.href.split(/[?#]/)[0],INITIAL=" + initial + ";",
+ "function post(m){m[K]=1;try{parent.postMessage(m,'*')}catch(_){}}",
+ "function report(){post({type:'location',value:L.search+L.hash})}",
+ "if(INITIAL){try{H.replaceState(H.state,'',BASE+INITIAL)}catch(_){}}",
+ "function resolve(u){if(typeof u!=='string')return u;var c=u.charAt(0);",
+ "if(c==='?')return BASE+u;if(c==='#')return BASE+L.search+u;return u}",
+ "['pushState','replaceState'].forEach(function(n){var o=H[n];if(typeof o!=='function')return;",
+ "H[n]=function(s,t,u){var r=arguments.length>2?o.call(H,s,t,resolve(u)):o.apply(H,arguments);report();return r}});",
+ "window.addEventListener('hashchange',report);window.addEventListener('popstate',report);",
+ // On window, in the bubble phase: after the author's handlers and the
+ // fragment-nav shim, so a click any of them claimed is left alone.
+ "window.addEventListener('click',function(e){",
+ "if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;",
+ "var t=e.target;if(!t||typeof t.closest!=='function')return;var a=t.closest('a[href]');if(!a)return;",
+ "var tg=a.getAttribute('target');if(tg&&tg!=='_self')return;var h=a.getAttribute('href')||'';",
+ "if(h.charAt(0)==='?'){e.preventDefault();post({type:'navigate',value:h})}",
+ "else if(h.charAt(0)==='#'&&h.length>1){e.preventDefault();L.hash=h}});",
+ "window.addEventListener('message',function(e){if(e.source!==parent)return;var d=e.data;",
+ "if(!d||d[K]!==1||d.type!=='hash'||typeof d.value!=='string')return;L.hash=d.value});",
+ // A document loaded at `#id` lands on that element, as it would in a tab.
+ "if(L.hash){window.addEventListener('load',function(){var id;try{id=decodeURIComponent(L.hash.slice(1))}catch(_){return}",
+ "var el=id&&document.getElementById(id);if(el)el.scrollIntoView()})}",
+ "report();",
+ "})();",
+ ].join("");
+}
+
+/** Exposed for tests so they can evaluate the script in jsdom. */
+export function __locationBridgeScript__(initialAddress: string): string {
+ return buildScript(initialAddress);
+}
+
+// A doctype must stay the first thing in the document or it renders in quirks
+// mode; comments may precede it.
+const LEADING_DOCTYPE_RE = /^\s*(?:<!--[\s\S]*?-->\s*)*<!doctype[^>]*>/i;
+
+/**
+ * The document with the bridge in front of the author's markup (after a
+ * leading doctype), loaded at `initialAddress`.
+ */
+export function withLocationBridge(html: string, initialAddress: string): string {
+ const prefix = `<script>${buildScript(initialAddress)}</script>`;
+ const doctype = LEADING_DOCTYPE_RE.exec(html)?.[0];
+ return doctype ? doctype + prefix + html.slice(doctype.length) : prefix + html;
+}
+
+/**
+ * What the reader typed, as the query-and-fragment the document is loaded
+ * at: `"?s=overview#top"`, or `""` for the bare document. The file name is
+ * the fixed part of the address, so a pasted `mock.html?s=x` keeps only its
+ * `?s=x`, and text with neither `?` nor `#` is read as a query.
+ */
+export function normalizeHtmlPreviewAddress(input: string, filename = ""): string {
+ const value = input.trim();
+ const start = value.search(/[?#]/);
+ const address =
+ start >= 0 ? value.slice(start) : value === "" || value === filename ? "" : `?${value}`;
+ return address.slice(0, HTML_PREVIEW_ADDRESS_MAX_LENGTH);
+}
+
+/** An address split into its query and fragment, each with its prefix. */
+export function splitHtmlPreviewAddress(address: string): { search: string; hash: string } {
+ const at = address.indexOf("#");
+ return at === -1
+ ? { search: address, hash: "" }
+ : { search: address.slice(0, at), hash: address.slice(at) };
+}
+
+export type HtmlPreviewLocationMessage =
+ | { type: "location"; value: string }
+ | { type: "navigate"; value: string };
+
+/**
+ * Parses a bridge message. Returns null for anything that is not one; the
+ * sandboxed document can post whatever it likes, so only a bounded
+ * query-or-fragment string gets through.
+ */
+export function readHtmlPreviewLocationMessage(
+ data: unknown,
+): HtmlPreviewLocationMessage | null {
+ if (typeof data !== "object" || data === null) return null;
+ const record = data as Record<string, unknown>;
+ if (record[HTML_PREVIEW_LOCATION_KEY] !== 1) return null;
+ const { type, value } = record;
+ if (type !== "location" && type !== "navigate") return null;
+ if (typeof value !== "string" || value.length > HTML_PREVIEW_ADDRESS_MAX_LENGTH) return null;
+ if (value !== "" && value[0] !== "?" && value[0] !== "#") return null;
+ if (type === "navigate" && value === "") return null;
+ return { type, value };
+}
diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.json
index fe566a44e4..5cb37a6e41 100644
--- a/packages/views/locales/en/editor.json
+++ b/packages/views/locales/en/editor.json
@@ -85,7 +85,10 @@
"table_rows_one": "{{count}} row",
"table_rows_other": "{{count}} rows",
"table_columns_one": "{{count}} column",
- "table_columns_other": "{{count}} columns"
+ "table_columns_other": "{{count}} columns",
+ "address": "Address",
+ "address_hint": "?query",
+ "reload": "Reload"
},
"link_hover": {
"copy_link": "Copy link",
diff --git a/packages/views/locales/fr/editor.json b/packages/views/locales/fr/editor.json
index f5afd8d7db..6eb9c50ff8 100644
--- a/packages/views/locales/fr/editor.json
+++ b/packages/views/locales/fr/editor.json
@@ -85,7 +85,10 @@
"table_rows_one": "{{count}} ligne",
"table_rows_other": "{{count}} lignes",
"table_columns_one": "{{count}} colonne",
- "table_columns_other": "{{count}} colonnes"
+ "table_columns_other": "{{count}} colonnes",
+ "address": "Adresse",
+ "address_hint": "?paramètres",
+ "reload": "Actualiser"
},
"link_hover": {
"copy_link": "Copier le lien",
diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.json
index aeb8f94a60..bef07f24a8 100644
--- a/packages/views/locales/ja/editor.json
+++ b/packages/views/locales/ja/editor.json
@@ -81,7 +81,10 @@
"tree_keys_other": "{{count}} 個のキー",
"table_empty": "行がありません",
"table_rows_other": "{{count}} 行",
- "table_columns_other": "{{count}} 列"
+ "table_columns_other": "{{count}} 列",
+ "address": "アドレス",
+ "address_hint": "?パラメータ",
+ "reload": "再読み込み"
},
"link_hover": {
"copy_link": "リンクをコピー",
diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.json
index 058c9ee68a..4738313fbc 100644
--- a/packages/views/locales/ko/editor.json
+++ b/packages/views/locales/ko/editor.json
@@ -81,7 +81,10 @@
"tree_keys_other": "키 {{count}}개",
"table_empty": "행이 없습니다",
"table_rows_other": "{{count}}행",
- "table_columns_other": "{{count}}열"
+ "table_columns_other": "{{count}}열",
+ "address": "주소",
+ "address_hint": "?매개변수",
+ "reload": "새로고침"
},
"link_hover": {
"copy_link": "링크 복사",
diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.json
index 9c1851e44c..ff6da59cf2 100644
--- a/packages/views/locales/zh-Hans/editor.json
+++ b/packages/views/locales/zh-Hans/editor.json
@@ -81,7 +81,10 @@
"tree_keys_other": "{{count}} 个键",
"table_empty": "没有数据行",
"table_rows_other": "{{count}} 行",
- "table_columns_other": "{{count}} 列"
+ "table_columns_other": "{{count}} 列",
+ "address": "地址",
+ "address_hint": "?参数",
+ "reload": "刷新"
},
"link_hover": {
"copy_link": "复制链接",